package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.SHOP_GEO_KEY;
import static com.hmdp.utils.SystemConstants.DEFAULT_PAGE_SIZE;

@Slf4j
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        //缓存穿透
        Shop shop = queryWithPassThrough(id);
        //利用工具类封装
        // Shop shop = cacheClient.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY, id,
        // Shop.class, this::getById,
        // RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);


        //利用互斥锁，解决缓存击穿
        //Shop shop = queryWithMutexLock(id);

        //逻辑过期解决缓存击穿
        // Shop shop = queryWithLogicalExpire(id);
        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    /**
     * 逻辑过期解决缓存击穿
     */
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public Shop queryWithLogicalExpire(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        //1.查询缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断缓存是否存在
        if (StrUtil.isBlank(shopJson)) {
            return null;
        }
        //3命中，需要把数据转为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //4判断逻辑过期
        //5.1未过期，返回数据
        if (expireTime.isAfter(LocalDateTime.now())) {
            return shop;
        }
        //5.2，过期，需要缓存重建
        //6.重建缓存
        //6.1获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        //6.2判断是否获取锁成功
        if (isLock) {
            //再次检测redis缓存是否过期，做DoubleCheck
            String doubleCheckCacheStr = stringRedisTemplate.opsForValue().get(key);
            RedisData redisData1 = JSONUtil.toBean(doubleCheckCacheStr, RedisData.class);
            LocalDateTime expireTime1 = redisData1.getExpireTime();
            Shop newShop = JSONUtil.toBean((JSONObject) redisData1.getData(), Shop.class);
            if (expireTime1.isAfter(LocalDateTime.now())) {
                //缓存未过期（已经有线程重建完成了），则返回数据
                return newShop;
            }
            //缓存未过期（已经有线程重建完成了），则返回数据
            //缓存仍过期 （还没有其他的线程重建缓存），创建独立线程，重建缓存
            //将重建工作交给线程池完成
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                //获取锁成功，开启独立线程，实现缓存重建
                try {
                    this.saveShop2Redis(id, 30L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unLock(lockKey);
                }
            });
        }
        //6.4 返回过期的商户信息
        return shop;
    }

    /**
     * 互斥锁解决缓存击穿
     */
    public Shop queryWithMutexLock(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        //1.查询缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断缓存是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //判断命中的是否是空值
        if (shopJson != null) {
            return null;
        }
        //3.实现缓存重建
        //3.1 获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lockKey);
            //3.2 判断是否获取锁成功
            if (!isLock) {
                //3.3失败，则休眠并重试
                Thread.sleep(50);
                return queryWithMutexLock(id);
            }
            //3.4成功，查询数据库
            shop = getById(id);
            if (shop == null) {
                //将空值写入redis，缓存穿透
                stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
                //返回错误信息
                return null;
            }
            //4.存在，写入缓存并返回
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //释放互斥锁
            unLock(lockKey);
        }
        //5.返回
        return shop;
    }
    //缓存穿透的代码封装在一起，封装成方法，用的时候调用这个方法

    /**
     * 缓存穿透
     */
    public Shop queryWithPassThrough(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        //1.查询缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断缓存是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //判断命中的是否是空值
        if (shopJson != null) {
            return null;
        }
        //3.不存在，查询数据库
        Shop shop = getById(id);
        if (shop == null) {
            //将空值写入redis，缓存穿透
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
            //返回错误信息
            return null;
        }
        //4.存在，写入缓存并返回
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }

    /**
     * 获取互斥锁
     */
    private boolean tryLock(String key) {
        //1.获取锁
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", RedisConstants.LOCK_SHOP_TTL, TimeUnit.SECONDS);
        //2.获取锁成功，返回true
        return BooleanUtil.isTrue(flag);
//        if(flag){
//            return true;
//        }
//        //3.获取锁失败，返回false
//        return false;
    }

    /**
     * 释放锁
     */
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    //逻辑过期解决缓存击穿
    public void saveShop2Redis(Long id, Long expireSeconds) {
        //1.查询店铺数据
        Shop shop = getById(id);
        //2.封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //3.写入redis
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }


    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不能为空");
        }
        //1.更新数据库
        updateById(shop);
        //2.删除缓存
        stringRedisTemplate.delete(RedisConstants.LOGIN_CODE_KEY + id);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {//current 页码
        log.info("current:{}", current);
        //1、判断需不需要根据坐标查询
        if (x == null || y == null) {
            //不需要按坐标查询，直接查询数据库
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }

        //2、计算分页参数
        int from = (current - 1) * DEFAULT_PAGE_SIZE;
        int end = current * DEFAULT_PAGE_SIZE;

        //3、查询Redis，按照距离排序、分页。结果：shopId、distance
        String key = SHOP_GEO_KEY + typeId;
        //查询以指定经纬度为圆心半径五公里的商铺
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(
                key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                //GEO的分页无法指定起始位置，只能从头读取指定条，此处先读取end条，之后再手动截取
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));
        if (results == null) {
            //五公里内没有店铺
            return Result.ok(Collections.emptyList());
        }

        //4、解析出店铺id及店铺距离
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            // 没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        //此时list中保存的是0 ~ end范围内的店铺，需要返回的是 from ~ end 范围内的店铺
        //4.1跳过前面的from条，截取 from ~ end内的
        ArrayList<Long> ids = new ArrayList<>(list.size());
        HashMap<String, Distance> distanceMap = new HashMap<>(list.size());
        if (list.size() <= from) {
            // 没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        list.stream().skip(from).forEach(result -> {
            //4.2、获取对应的店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            //4.3、获取对应店铺的距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });

        //5、根据id查询商铺
        String idStr = StrUtil.join(",", ids);
        List<Shop> shopList = query().in("id", ids).last("ORDER BY FIELD ( id," + idStr + ")").list();
        for (Shop shop : shopList) {
            //设置店铺距离字段
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }

        //6、返回结果
        return Result.ok(shopList);
    }
}
